import { Controller, Get, Post, Body, Param, Delete, UseGuards, UnauthorizedException, Query } from '@nestjs/common';
import { CommentService } from './comment.service';
import { CreateCommentDto } from './dto/create-comment.dto';
import { Comment } from './entities/comment.entity';

@Controller('comments')
export class CommentController {
  constructor(private readonly commentService: CommentService) {}

  @Post()
  create(@Body() createCommentDto: CreateCommentDto): Promise<Comment> {
    return this.commentService.create(createCommentDto);
  }

  @Get('post/:postId')
  findByPost(
    @Param('postId') postId: string,
    @Query('page') page: number = 1,
    @Query('limit') limit: number = 50
  ): Promise<Comment[]> {
    // 确保页码和限制是有效数字
    const pageNum = page ? Math.max(1, +page) : 1;
    const limitNum = limit ? Math.min(100, Math.max(1, +limit)) : 50;
    
    return this.commentService.findByPost(postId, pageNum, limitNum);
  }

  @Delete(':id')
  async remove(@Param('id') id: string, @Body('userId') userId: string): Promise<void> {
    // Check if user is the comment author
    const comment = await this.commentService.findOne(id);
    if (comment.authorId !== userId) {
      throw new UnauthorizedException('You are not authorized to delete this comment');
    }
    return this.commentService.remove(id);
  }
} 